<template>
  <div>
    <el-table :data="message" style="width: 100%">
      <el-table-column fixed label="序号" width="120">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="true" prop="id" label="id" width="120"/>
      <el-table-column prop="username" label="username" width="auto"/>
      <el-table-column prop="password" label="password" width="auto"/>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" size="default" @click="goToEdit(row.id)">修改</el-button>
          <el-button link type="danger" size="default" @click="showConfirm(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <div style="display: flex; align-items: center; justify-content: space-between;">
      <el-button type="primary" @click="prevPage">上一页</el-button>
      <div style="margin: 0 10px;">当前页：{{ currentPage }} / {{ totalPage }}</div>
      <div style="margin: 0 10px;">总数量：{{ totalDatas }}</div>
      <div>
        <span>每页显示：</span>
        <el-input v-model.number="pageSize" @change="changePageSize" style="width: 50px;"></el-input>
      </div>
      <el-button type="primary" @click="nextPage">下一页</el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, watchEffect} from 'vue';
import axios from 'axios';
import {urlData} from '../utils/url';
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();
const message = ref([]);
const currentPage = ref(1);
const pageSize = ref(10); // 默认每页显示10条数据
let totalPage = ref(1); // 总页数
let totalDatas = ref(0); // 总数据量
//加载数据
const fetchData = () => {
  axios.get(urlData('getAllUsers'), {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(res => {
    message.value = res.data.data;
    totalDatas.value = res.data.total;
    totalPage.value = Math.ceil(res.data.total / pageSize.value);
    if (currentPage.value > totalPage.value) {
      currentPage.value = totalPage.value;
    }
  }).catch(error => {
    console.log('error=>', error);
  });
};
//跳转页面
const goToEdit = (id) => {
  console.log('goToEditId=>', id)
  router.push({name: 'edit', params: {id}})
}
//删除用户
const showConfirm = (id) => {
  //获取这一行的数据
  const row = message.value.find(item => item.id === id);
  ElMessageBox.confirm(`确认要删除用户{${row.username}}吗?`, '删除提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(id);
  }).catch(() => {
  });
};
const deleteUser = (id) => {
  // 发送DELETE请求到后端删除用户
  fetch(`${urlData('deleteUser')}/${id}`, {
    method: 'DELETE'
  }).then(response => {
    if (response.ok) {
      // message.value = message.value.filter(item => item.id !== id)

      fetchData();

      console.log('User deleted successfully');

      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败');
      console.error('Failed to delete user');
    }
  }).catch(error => {
    console.error('Error occurred while deleting user:', error);
  });
};

//分页相关函数
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchData(); // 重新获取数据
  } else {
    ElMessage.error('已经是第一页');
  }
};

const nextPage = () => {
  if (currentPage.value < totalPage.value) {
    currentPage.value++;
    fetchData(); // 重新获取数据
  } else {
    ElMessage.error('已经是最后一页');
  }
};

const changePageSize = () => {
  currentPage.value = 1; // 切换每页大小后将当前页重置为第一页
  fetchData(); // 输入 pageSize 值后重新获取数据
};

watchEffect(pageSize, () => {
  fetchData(); // 监听 pageSize 的变化，重新获取数据
});

fetchData(); // 初始化时获取第一页的数据
</script>
<style scoped>

</style>
